package com.yanzhen.front;

import com.github.pagehelper.PageInfo;
import com.hankcs.hanlp.classification.utilities.io.ConsoleLogger;
import com.yanzhen.entity.Intention;
import com.yanzhen.entity.Post;
import com.yanzhen.entity.Resume;
import com.yanzhen.framework.recommend.CosineSimilarity;
import com.yanzhen.framework.recommend.Recommend;
import com.yanzhen.framework.redis.RedisUtil;
import com.yanzhen.service.IntentionService;
import com.yanzhen.service.PostService;
import com.yanzhen.service.ResumeService;
import com.yanzhen.service.UserDataService;
import com.yanzhen.utils.MahoutUtils;
import com.yanzhen.utils.Result;
import com.yanzhen.vo.UserData;
import org.apache.mahout.cf.taste.common.TasteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/f/post/")
public class PostFront {

    @Autowired
    PostService postService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ResumeService resumeService;
    @Autowired
    private IntentionService intentionService;

    @PostMapping("query")
    public Map<String,Object> getPostList(@RequestBody HashMap<String,Object> map, HttpServletRequest request){
        String token = request.getHeader("token");
        UserData userData = null;
        if(StringUtils.hasLength(token)){
            userData = (UserData) redisUtil.get(token);
        }
        PageInfo<HashMap> postList = postService.getPostList(map);
        boolean flag = false;//是否存在搜索添加
        for (Map.Entry entry : map.entrySet()) {
            if(!"page".equals(entry.getKey())){
                System.out.println(entry.getKey()+","+entry.getValue());
                if(StringUtils.hasLength(entry.getValue()+"")){
                    flag = true;
                }
            }
        }
        if(flag&&StringUtils.hasLength(token)){
            //排在前几条的吻合度较高的数据
            List<HashMap> list = postList.getList();
            if(list.size()>5){
                List<HashMap> subList = list.subList(0, 5);
                for (HashMap hashMap:subList){
                    HashMap hm = new HashMap();
                    hm.put("uid",userData.getId());
                    hm.put("iid",hashMap.get("id"));
                    hm.put("val",1);
                    saveOrUpdate(hm);
                }
                //保存感匹配度较高的前10条数据
            }else if(list.size()<=5 && list.size()>0){
                for (HashMap hashMap:postList.getList()){
                    HashMap hm = new HashMap();
                    hm.put("uid",userData.getId());
                    hm.put("iid",hashMap.get("id"));
                    hm.put("val",1);
                    saveOrUpdate(hm);
                }
            }

        }
        return Result.ok(postList);
    }

    public void saveOrUpdate(HashMap hm){
        int i = postService.countMahout(hm);
        if(i>0){
            postService.updateMahout(hm);
        }else{
            postService.createMahout(hm);
        }

    }

    /*@PostMapping("recommend")
    public Map<String,Object> getRecommendPost(@RequestBody HashMap<String,Object> map, HttpServletRequest request){

        String token = request.getHeader("token");
        UserData userData = null;
        if(StringUtils.hasLength(token)){
            userData = (UserData) redisUtil.get(token);
        }
        List<HashMap> list = new ArrayList<>();
        try {
            List<Long> recommendList = MahoutUtils.getRecommendPost(userData.getId());
            for (Long lo : recommendList) {
                map.put("id",lo);
                PageInfo<HashMap> postList = postService.getPostList(map);
                list.add(postList.getList().get(0));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TasteException e) {
            e.printStackTrace();
        }
        PageInfo<HashMap> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(1);
        pageInfo.setPageSize(10);
        pageInfo.setTotal(10);
        pageInfo.setList(list);
        return Result.ok(pageInfo);

    }*/

    @PostMapping("recommend")
    public Map<String,Object> getRecommendPost(@RequestBody HashMap<String,Object> map, HttpServletRequest request){

        String token = request.getHeader("token");
        UserData userData = null;
        if(StringUtils.hasLength(token)){
            userData = (UserData) redisUtil.get(token);
        }
        Resume param = new Resume();
        param.setStudentId(userData.getId());
        PageInfo<Resume> pageInfo = resumeService.query(param);
        if(pageInfo == null || pageInfo.getList() == null){
            return Result.ok(pageInfo);
        }
        Resume resume = pageInfo.getList().get(0);
        Intention iParam = new Intention();
        iParam.setStudentId(userData.getId());
        iParam.setResumeId(resume.getId());
        PageInfo<Intention> intentionPageInfo = intentionService.query(iParam);
        if(intentionPageInfo.getList() == null){
            return Result.ok(intentionPageInfo);
        }
        Intention intention = intentionPageInfo.getList().get(0);

        StringBuffer all = new StringBuffer();
        all.append(resume.getEvaluate()).append(resume.getSkill())
                .append(intention.getCity())
                .append(intention.getIndustry())
                .append(intention.getName())
                .append(intention.getType())
                .append(intention.getSalary());
        List<Post> list = postService.query();
        List<Recommend> result = new ArrayList<>();
        for (Post post : list) {
            StringBuffer sb = new StringBuffer();
            sb.append(post.getName()).append(post.getEducation()).append(post.getSalary()).append(post.getDescription());
            double score= CosineSimilarity.getSimilarity(all.toString(),sb.toString());
            Recommend recommend = new Recommend(post.getId(),score);
            result.add(recommend);
            System.out.println("参考。。。。"+score);
        }
        Collections.sort(result, new Comparator<Recommend>() {
            @Override
            public int compare(Recommend o1, Recommend o2) {
                if(o1.getScore() - o2.getScore()>0){
                    return -1;
                }else if(o1.getScore() == o2.getScore()){
                    return 0;
                }else{
                    return 1;
                }
            }
        });
        List<Recommend>  _list = new ArrayList();
        int i = 0;
        for (Recommend recommend : result) {
            if(i++<10){
                _list.add(recommend);
            }
        }
        List<HashMap> rlist = new ArrayList<>();
        for (Recommend r : _list) {
            map.put("id",r.getId());
            PageInfo<HashMap> postList = postService.getPostList(map);
            rlist.add(postList.getList().get(0));
        }
        PageInfo<HashMap> pageInfo2 = new PageInfo<>();
        pageInfo2.setPageNum(1);
        pageInfo2.setPageSize(10);
        pageInfo2.setTotal(10);
        pageInfo2.setList(rlist);
        return Result.ok(pageInfo2);

    }

}
